package com.example.authservice.serviceImpl;

import com.example.api.service.OpenApiAppService;
import com.example.authservice.tool.OpenApiAppTools;
import com.example.common.entity.CallbackConfig;
import com.example.common.entity.OpenApiApp;
import com.example.common.entity.vo.AppInfoVO;
import com.example.common.exception.BaseException;
import com.example.common.exception.ExceptionCode;
import com.example.common.mapper.OpenApiAppMapper;
import com.example.common.utils.WillingAESUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author DestinyCc
 * @date 2022/4/15
 */
@Service(protocol = "dubbo")
@Slf4j
public class OpenApiAppServiceImpl implements OpenApiAppService {

    @Value("${server.port}")
    String port;

    @Autowired
    OpenApiAppMapper openApiAppMapper;

    @Override
    @SneakyThrows
    public AppInfoVO createApp(String email) {
        String regex = "^(\\w+((-\\w+)|(.\\w+)))+\\w+((-\\w+)|(.\\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+)*.[A-Za-z0-9]+$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(email);
        if (!matcher.matches()){
            throw new BaseException(ExceptionCode.PARAM_NOT_VALID, "email不合法");
        }
        List<OpenApiApp> apps = openApiAppMapper.listAllByEmail(email);
        if (CollectionUtils.isNotEmpty(apps)){
            log.info("email = {} 开放平台应用已存在", email);
            OpenApiApp app = apps.get(0);
            return new AppInfoVO(app.getAppId(), WillingAESUtils.decrypt(app.getAppSecret()));
        }
        String appId = OpenApiAppTools.calculateAppId(email);
        String secret = OpenApiAppTools.calculateSecret(email, appId);
        OpenApiApp openApiApp = OpenApiAppTools.initOpenApiApp(email, appId, secret);
        openApiAppMapper.insertSelective(openApiApp);
        return new AppInfoVO(appId, secret);
    }

    @Override
    public OpenApiApp getAppByAppIdAndSecret(String appId, String appSecret) {
        return openApiAppMapper.getByAppIdSecret(appId, appSecret);
    }

    @Override
    public void updateByPrimaryKeySelective(OpenApiApp apiApp) {
        openApiAppMapper.updateByPrimaryKeySelective(apiApp);
    }

    @Override
    public CallbackConfig getCallbackCfgByIdAndAppId(String id, String appId) {
        OpenApiApp app = openApiAppMapper.getByIdAppId(id, appId);
        if (Objects.nonNull(app)){
            return new CallbackConfig(app.getAppId(), app.getId(), app.getToken(), app.getEncodingAesKey(), app.getCallbackUrl());
        }
        return null;
    }

}
